using UnityEngine;
using System.Collections;

/* TODO:
 * 1- Think of a better way to lunge
 * 2- Refactor...resembleance to the MouseLook script is NOT mere coincidence
 * 3- Any and hopefully everything that comes up.
 */

public class LanceControll : MonoBehaviour {

	public enum RotationAxes { MouseXAndY = 0, MouseX = 1, MouseY = 2 }
	public RotationAxes axes = RotationAxes.MouseXAndY;
	public float sensitivityX = 15F;
	public float sensitivityY = 15F;

	public float minimumX = -360F;
	public float maximumX = 360F;

	public float minimumY = -60F;
	public float maximumY = 60F;
	
	private float rotationX = 330F;
	private float rotationY = 0F;
	
	private float maxLunge = 1.5F;
	private float currentLungeAmmount = 0F;
	private bool isReturningFromLunge;
	private bool hasHit;
	private bool isLunging;

	void Update ()
	{
		if (!hasHit) {
			// small lance weight simulation
			rotationY -= 0.04F;
			if (axes == RotationAxes.MouseXAndY) {
				// Fixing some issues with Maximum and Minimum X not working at all
			    if (minimumX == maximumX) {
			       rotationX = transform.localEulerAngles.y + Input.GetAxis("Mouse X") * sensitivityX;
			    }
			    else {
			       rotationX += Input.GetAxis("Mouse X") * sensitivityX;
			       rotationX = Mathf.Clamp(rotationX, minimumX, maximumX);          
			    }
			    rotationY += Input.GetAxis("Mouse Y") * sensitivityY;
			    rotationY = Mathf.Clamp (rotationY, minimumY, maximumY);
			    transform.localEulerAngles = new Vector3(-rotationY, rotationX, 0);
			}
			else if (axes == RotationAxes.MouseX)
			{
				transform.Rotate(0, Input.GetAxis("Mouse X") * sensitivityX, 0);
			}
			else
			{
				rotationY += Input.GetAxis("Mouse Y") * sensitivityY;
				rotationY = Mathf.Clamp (rotationY, minimumY, maximumY);
				
				transform.localEulerAngles = new Vector3(-rotationY, transform.localEulerAngles.y, 0);
			}
			
			if (Input.GetMouseButton(0) && !isLunging)
				isLunging = true;
			if (isLunging)
				executeLunge(0.2F);
		}
	}
	
	void Start ()
	{
		
	}
	
	// Still strange, can't use only the Z axis...but I'm leaving it at that for now
	// Might be better left of to a animation...
	private void executeLunge(float lungeByZ)
	{
		Vector3 lungeBy = new Vector3(0, 0, lungeByZ);
		if (currentLungeAmmount >= maxLunge) {
			isReturningFromLunge = true;
		}
		else if (currentLungeAmmount <= 0F) {
			isReturningFromLunge = false;
			isLunging = false;
		}
		
		if (isReturningFromLunge) {
			transform.position -= lungeBy;
		currentLungeAmmount -= lungeByZ;
		} else {
			transform.position += lungeBy;
		currentLungeAmmount += lungeByZ;
		}
	}
	
	public void setHasHit(bool hasHit)
	{
		this.hasHit = hasHit;
	}
}